package org.sshbot;

import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import org.sshbot.transport.SSH;
import org.sshbot.transport.Transport;
import org.sshbot.util.LogHelper;
import org.sshbot.util.Utils;

import com.jcraft.jsch.JSchException;
import com.securecrt.SaveSession;
import com.securecrt.pojo.SQLHelper;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class Ssh extends Activity{

	public static boolean isPortrait = true;

	private Transport transport;
	
	EditText host, port, user, pass;
	Button btnConn;
	Button btBack, btHome ,btvn,bten,btkr;;
	TextView tvlinksession;
	Spinner protocol, cipher, mac;
	ProgressDialog pro;
	CheckBox save_session;
	private boolean checked=false;
	SQLHelper eventsData;
	
	/**
	 * Called when the activity is first created.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		LogHelper.register(this);

		super.onCreate(savedInstanceState);
		setContentView(R.layout.ssh);

		 	protocol = (Spinner)findViewById(R.id.protocol);
	        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.protocol ,android.R.layout.simple_spinner_item);
	        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	        protocol.setAdapter(adapter);
	        protocol.setSelection(2);
	        protocol.setOnItemSelectedListener(new OnItemSelectedListener() {

				@Override
				public void onItemSelected(AdapterView<?> parent, View arg1,
						int position, long arg3) {
					String name = parent.getItemAtPosition(position).toString();
					if(name.equals("ssh")){
						return;
					}
					String classSelected = "org.sshbot." + name.toUpperCase();System.out.println(name+" :classSelected: "+classSelected);
					Intent intent = new Intent(classSelected);
					startActivity(intent);
					finish();
				}

				@Override
				public void onNothingSelected(AdapterView<?> arg0) {
					// TODO Auto-generated method stub
					
				}
			});
	        
	        host=(EditText)findViewById(R.id.etHostname);
	        user=(EditText)findViewById(R.id.etUsername);
	        pass=(EditText)findViewById(R.id.etPassword);
	        port=(EditText)findViewById(R.id.etPort);
	        
	        btnConn=(Button)findViewById(R.id.btnConnect);
	        btnConn.setOnClickListener(onClickListenerConn);
	        btBack = (Button) findViewById(R.id.btBack);
			btHome = (Button) findViewById(R.id.btHome);
			btBack.setOnClickListener(onBackClick());
			btHome.setOnClickListener(onHomeClick());
			
			btvn=(Button)findViewById(R.id.btvn);btvn.setOnClickListener(onClickbtvn());
		    bten=(Button)findViewById(R.id.bten);bten.setOnClickListener(onClickbten());
		    btkr=(Button)findViewById(R.id.btkr);btkr.setOnClickListener(onClickbtkr());
	        tvlinksession=(TextView)findViewById(R.id.tvlinksession);
	        tvlinksession.setOnClickListener(OnClickLinksession);
			save_session=(CheckBox)findViewById(R.id.save_session);
	        save_session.setOnCheckedChangeListener(ChecKedChangeListener);
	        eventsData=new SQLHelper(this);
	        
	}

	private OnCheckedChangeListener ChecKedChangeListener=new OnCheckedChangeListener() {
		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			// TODO Auto-generated method stub
			if(buttonView.isChecked()){
				checked=true;
			}else{
				checked=false;
			}
		}
	};
    private void passSaveSession(){
    	Intent i=new Intent(this, SaveSession.class);
    	i.putExtra("host",host.getText().toString());
		i.putExtra("user", String.valueOf(user.getText().toString()));
    	startActivity(i);
    }
    private OnClickListener OnClickLinksession=new OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			passSaveSession();
		}
	};
	private String outDateCurrent(){
		String result="";
		DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		Date date = new Date();
		return result=dateFormat.format(date);
	}
    private void saveSessionActive(){
    	SQLiteDatabase db=eventsData.getWritableDatabase();
		ContentValues values=new ContentValues();
		values.put(SQLHelper.HOSTNAME, host.getText().toString());
		values.put(SQLHelper.PORT, port.getText().toString());
		values.put(SQLHelper.USERNAME, String.valueOf(user.getText().toString()));
		values.put(SQLHelper.PASSWORD, pass.getText().toString());
		String cuDate = outDateCurrent();
		values.put(SQLHelper.TIME_, cuDate);
		db.insert(SQLHelper.SESSION, null, values);
    }
	
	 private OnClickListener onClickListenerConn=new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				final String hotname=host.getText().toString();
				final int p=Integer.parseInt(port.getText().toString());
				final String username=user.getText().toString();
				final String password=pass.getText().toString();
				
				if(hotname.trim().equals("")){
					Utils.showErrorMessage(Ssh.this,getString(R.string.errHost));					    		
		    		return;
				}
		    	if(username.trim().equals("")){
		    		Utils.showErrorMessage(Ssh.this,getString(R.string.errUser));					    		
		    		return;
				}
		    	if(password.trim().equals("")){
		    		Utils.showErrorMessage(Ssh.this,getString(R.string.errPass));						    		
		    		return;
				}
		    	String sPort=port.getText().toString().trim();
		    	boolean isBadPort=false;
		    	int iPort=0;
		    	try{
		    		iPort=Integer.parseInt(sPort);
		    	}
		    	catch (Exception e) {
					isBadPort=true;
				}
		    	if(iPort<=0||iPort>=65535){
		    		isBadPort=true;
		    	}
		    	if(isBadPort){
		    		Utils.showErrorMessage(Ssh.this,getString(R.string.errPort));					    		
		    		return;
		    	}
		    	try {
					connection(username,password, hotname,iPort);
				} catch (UnknownHostException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
		private boolean showEvents(Cursor cursor){
			boolean ch=false;
			String ho=host.getText().toString();
			String po=port.getText().toString();
			String us=String.valueOf(user.getText().toString());
			String pa=pass.getText().toString();
			while(cursor.moveToNext()){
				long id =cursor.getLong(0);
				String hostname=cursor.getString(1);
				String port=cursor.getString(2);
				String username=cursor.getString(3);
				String password=cursor.getString(4);
				if(hostname.equals(ho)&&port.equals(po)&&username.equals(us)&&password.equals(pa))
					return ch=true;
			}
			return ch;
		}
	    private Cursor getEvents(){
			SQLiteDatabase db=eventsData.getReadableDatabase();
			Cursor cursor=db.query(SQLHelper.SESSION, null, null, null, null,null, null);
			startManagingCursor(cursor);
			return cursor;
		}
	    private boolean checkSession(){
	    	boolean ch=false;
	    	Cursor cursor=getEvents();
	        if(showEvents(cursor))
	        	return ch=true;
	        return ch;
	    }
		public void connection(String username, String password,String hotname, int port) throws UnknownHostException{
			boolean res = connectToServer(username+"@"+password+"@"+hotname+"@"+port);
			if (res) {
        		if(checked && !checkSession()){
					//save session
					saveSessionActive();
				}
			}else{
				Utils.showErrorMessage(Ssh.this,"SSH Connect Fault.");
				//Toast.makeText(Ssh.this,"SSH Connect Fault.", Toast.LENGTH_SHORT).show();			
				return;
			}
		}
		private OnClickListener onBackClick() {
			OnClickListener onBackClick = new OnClickListener() {
				@Override
				public void onClick(View v) {
					//moveTaskToBack(true);	
					finish();
					System.exit(0);
				}
			};
			return onBackClick;
		}
		
		private OnClickListener onHomeClick() {
			OnClickListener onHomeClick = new OnClickListener() {
				@Override
				public void onClick(View v) {

					Intent intent = new Intent(Intent.ACTION_MAIN);
					intent.addCategory(Intent.CATEGORY_HOME);
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(intent);
					finish();
					System.exit(0);

				}
			};
			return onHomeClick;
		}	
   
	
	 private OnClickListener onClickbtvn(){
	    	OnClickListener onClickbtvn=new OnClickListener() {
				@Override
				public void onClick(View v) {
					changuageLang("vn");refresh();
				}
			};
	    	return onClickbtvn;
	    }
	    private OnClickListener onClickbten(){
	    	OnClickListener onClickbten=new OnClickListener() {
				@Override
				public void onClick(View v) {
					changuageLang("en");refresh();
				}
			};
	    	return onClickbten;
	    }

	    private OnClickListener onClickbtkr(){
	    	OnClickListener onClickbtkr=new OnClickListener() {
				@Override
				public void onClick(View v) {
					changuageLang("kr");refresh();
				}
			};
	    	return onClickbtkr;
	    }
	    
	    private void changuageLang(String lang){
			Locale locale=new Locale(lang);
	        Locale.setDefault(locale);
	        Configuration config=new Configuration();
	        config.locale=locale;
	        getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
	    }
	    
	    private void refresh() {
	        finish();
	        Intent myIntent = new Intent(Ssh.this, Ssh.class);
	        startActivity(myIntent);
	    }
	    
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);

		// TODO save this to somewhere better place
		isPortrait = newConfig.orientation == Configuration.ORIENTATION_PORTRAIT;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

//		transport.disconnect();
	}

	private SSH sh;
	private boolean connectToServer(final String uri) throws UnknownHostException {
		if (!uri.contains("@")) {
			return false;
		}

		String[] tmp = uri.split("@");
		String username = tmp[0];
		String pass = tmp[1];
		String host = tmp[2];		
		int port = Integer.parseInt(tmp[3]);
		

		transport = null;
		sh = null;
		try {
			sh = new SSH(username,pass, host, port);			
		} catch (JSchException e) {
			e.printStackTrace();			
		}

		if(sh.isConnected()){
			transport = sh;
		}else{
			return false;
		}
		
		if (transport != null) {
			TerminalView tv = new TerminalView(this, transport);
			
			setContentView(tv);
		}

		return true;
	}

}
